package com.alpsot.spotcheck.activity;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alpsoft.spotcheck.adapter.HorizontalListViewAdapter;
import com.alpsoft.spotcheck.db.DBManager;
import com.alpsoft.spotcheck.db.SQLiteTemplate;
import com.alpsoft.spotcheck.db.SQLiteTemplate.RowMapper;
import com.alpsoft.spotcheck.model.Attachment;
import com.alpsoft.spotcheck.model.Exception;
import com.alpsoft.spotcheck.ui.HorizontalListView;
import com.alpsoft.spotcheck.util.GlobalVar;
import com.alpsoft.spotcheck.util.ImgUtil;
import com.alpsot.lkspotcheck.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 异常记录和照片缓存窗体
 * @author Nasir
 *
 */
@ContentView(R.layout.activity_exception_listview)
public class ExceptionActivity extends BaseActivity {
	
	@ViewInject(R.id.exp_pic)
	private Button exp_pic;
	@ViewInject(R.id.exp_save)
	private Button exp_save;
	@ViewInject(R.id.exp_back)
	private Button exp_back;
	
	private HorizontalListView hListView;
	private HorizontalListViewAdapter hListViewAdapter;
//	ImageView previewImg;
	View olderSelectView = null;
	
	public static String filename = "";
	public static String picPath = GlobalVar.picPath;
	private DBManager dbManager;
//	private String record_id;
	private SQLiteTemplate st;
	private String exp_id = "";
	private String belongEq;
	private String cycle_type;
	private String listViewPos;
	private String isCheckMan;
	private final String REPORT = "上报异常信息";
	private final String REPAIR = "点检人自行修复";
	private final String OBSERVE = "继续观察重点跟踪";
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		dbManager = DBManager.getInstance(this, GlobalVar.databaseName);
		st = SQLiteTemplate.getInstance(dbManager, false);
		Intent intent = this.getIntent();//得到激活她的意图  
        exp_id = intent.getStringExtra("exp_id");  
        belongEq = intent.getStringExtra("belongEq");  
        cycle_type = intent.getStringExtra("cycle_type");
        listViewPos = intent.getStringExtra("position");
        isCheckMan = intent.getStringExtra("isCheckMan");
        if("true".equals(isCheckMan)){
        	exp_back.setVisibility(View.GONE);
        }else if("false".equals(isCheckMan)){
        	exp_pic.setVisibility(View.GONE);
        	exp_save.setVisibility(View.GONE);
        }
        
        
        
        
        Exception exp = st.queryForObject(new RowMapper<Exception>() {

			@Override
			public Exception mapRow(Cursor cursor, int index) {
				// TODO Auto-generated method stub
				Exception exp = new Exception();
				exp.setSubmitContent(cursor.getString(cursor.getColumnIndex("SUBMIT_CONTENT")));
				exp.setFlag(cursor.getString(cursor.getColumnIndex("FLAG")));
				
				return exp;
			}
		}, "select * from RP_EXCEPTION_SUBMIT where EXCEPTION_SUBMIT_ID=?", new String[] { exp_id });
        		
     	EditText et = (EditText)findViewById(R.id.editText1);
     	et.setText(exp.getSubmitContent());
     	
     	String dbFlag = exp.getFlag();
     	if("sb".equals(dbFlag)){
     		((RadioButton)findViewById(R.id.report)).setChecked(true);
     	}else if("zx".equals(dbFlag)){
     		((RadioButton)findViewById(R.id.repair)).setChecked(true);
     	}else if("gc".equals(dbFlag)){
     		((RadioButton)findViewById(R.id.observe)).setChecked(true);
     	}
     	
     	File file = new File(picPath);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
		}
     	
      	initUI();
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void initUI(){
		hListView = (HorizontalListView)findViewById(R.id.horizon_listview);
//		previewImg = (ImageView)findViewById(R.id.image_preview);
		List<Attachment> attachList = st.queryForList(new RowMapper<Attachment>() {

			@Override
			public Attachment mapRow(Cursor cursor, int index) {
				// TODO Auto-generated method stub
				Attachment am = new Attachment();
				am.setFilePath(cursor.getString(cursor.getColumnIndex("FILE_PATH")));
				return am;
			}
		}, "select * from EQ_ATTACHMENT where TABLE_NAME=? and KEY=? and VALUE=?", new String[]{"RP_EXCEPTION_SUBMIT","EXCEPTION_SUBMIT_ID",exp_id});
		String[] srcArr = null;
		if(null!=attachList&&!attachList.isEmpty()){
			srcArr = new String[attachList.size()];
			for(int i=0;i<attachList.size();i++){
				Attachment ac = attachList.get(i);
				srcArr[i] = ac.getFilePath();
			}
			
		}else{
			String fileName = "no_pic.jpg";
			String path = ImgUtil.copyToSD(this, fileName);
			srcArr = new String[]{path};
		}
		
//		final String finalSrcArr[] = srcArr;
		hListViewAdapter = new HorizontalListViewAdapter(getApplicationContext(),srcArr);
		hListView.setAdapter(hListViewAdapter);
//		hListView.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				// TODO Auto-generated method stub
//				Bitmap bm = BitmapFactory.decodeFile(finalSrcArr[position]); 
//				previewImg.setImageBitmap(bm);
//				hListViewAdapter.setSelectIndex(position);
//				hListViewAdapter.notifyDataSetChanged();
//			}
//		});

	}

	@Override
	public Handler getHandler() {
		return null;
	}

	@OnClick(R.id.exp_pic)
	private void take_pictures(View v){
		Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		filename = System.currentTimeMillis() + ".jpg";
		it.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(picPath + filename)));
		startActivityForResult(it, 1);
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
				Log.i("TestFile","SD card is not avaiable/writeable right now.");
				return;
			}

//			Bitmap bitmap = null;
			try {
				StringBuilder sb = null;
		    	Object[] args = new Object[]{filename,picPath + filename,"RP_EXCEPTION_SUBMIT","EXCEPTION_SUBMIT_ID",exp_id};
		    	sb = new StringBuilder();
		    	sb.append("insert into EQ_ATTACHMENT ");
		    	sb.append("(ATTACHMENT_NAME,FILE_PATH,TABLE_NAME,KEY,VALUE) ");
		    	sb.append("VALUES ");
		    	sb.append("(?,?,?,?,?)");
		    	st.execSQL(sb.toString(), args);
//		    	bitmap = BitmapUtil.getimage(picPath + filename) ;
		    	initUI();
		    	
			} catch (java.lang.Exception e) {
				e.printStackTrace();
			}
		}
	}
	@OnClick(R.id.exp_save)
	private void save(View v){
		RadioGroup radioGroup = (RadioGroup)findViewById(R.id.handleWay);
		RadioButton radioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
		EditText et = (EditText)findViewById(R.id.editText1);
		if(null==radioButton||TextUtils.isEmpty(et.getText())){
			Toast toast = Toast.makeText(getApplicationContext(),
					"请先选择异常类型再进行保存操作", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}else{
			String flag = "";
			String flagStr = radioButton.getText().toString();
			if(REPORT.equals(flagStr)){
				flag = "sb";
			}else if(REPAIR.equals(flagStr)){
				flag = "zx";
			}else if(OBSERVE.equals(flagStr)){
				flag = "gc";
			}
			
			String content = et.getText().toString();
			StringBuilder sb = new StringBuilder();
			sb.append("update RP_EXCEPTION_SUBMIT ");
			sb.append("set SUBMIT_CONTENT=?,FLAG=? ");
			sb.append("where EXCEPTION_SUBMIT_ID=?");
			st.execSQL(sb.toString(), new Object[]{content, flag, exp_id});
			
			Intent intent = new Intent();
	        intent.putExtra("belongEq", belongEq);
	        intent.putExtra("cycle_type", cycle_type);
	        intent.putExtra("isCheckMan", isCheckMan);
			intent.setClass(ExceptionActivity.this, CheckItemActivity.class); 
			startActivity(intent);  
//			Intent intent = new Intent();  
//	        intent.putExtra("belongEq", belongEq);  
//	        intent.putExtra("cycle_type", cycle_type); 
//	        intent.putExtra("position", String.valueOf(listViewPos));
//	        setResult(2, intent);  
	        finish();  
		}
		
	}
	
	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(this).setTitle("是否删除异常?")
		.setIcon(android.R.drawable.ic_dialog_info)
		.setCancelable(false)
		.setPositiveButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		})
		.setNegativeButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				CheckItemActivity.temMap=CheckItemActivity.listData.get(CheckItemActivity.listViewPos);
				CheckItemActivity.temMap.put("it_type", "√");
				CheckItemActivity.temMap.put("show", "√");
				CheckItemActivity.temMap.put("is_exception", "no");
				CheckItemActivity.listAdapter.notifyDataSetChanged();
				new CheckItemActivity().clearExceptionInfo();
				finish();
			}
		}).show();
	}
	
	@OnClick(R.id.exp_back)
	private void back(View v){
		Intent intent = new Intent();  
        intent.putExtra("belongEq", belongEq);  
        intent.putExtra("cycle_type", cycle_type); 
        intent.putExtra("position", String.valueOf(listViewPos));
        setResult(3, intent);  
        finish(); 
	}
	
}

